// Pinia store: 管理书籍列表 / 详情 / 章节缓存
import { defineStore } from 'pinia'
import { fetchBooks, fetchBookDetail, fetchBookContent } from '@/api/books'

export const useBooksStore = defineStore('books', {
  state: () => ({
    list: [],
    listLoading: false,
    listError: null,
    pagination: { page: 1, page_size: 50, total: 0 },

    detailMap: {}, // { [id]: bookDetail }
    detailLoadingMap: {}, // { [id]: boolean }
    detailErrorMap: {},

    chapterCache: {}, // { [bookId]: { [chapterId]: chapterData } }
    activeBookId: null,
    activeChapterId: null
  }),
  getters: {
    activeBook(state) {
      if (!state.activeBookId) return null
      return state.detailMap[state.activeBookId] || null
    },
    chaptersOfActive(state) {
      return state.activeBook?.content?.chapters || []
    }
  },
  actions: {
    async loadBooks(params = {}) {
      this.listLoading = true
      this.listError = null
      try {
        const data = await fetchBooks(params)
        this.list = data.items || []
        this.pagination = {
          page: data.page || params.page || 1,
          page_size: data.page_size || params.page_size || 50,
          total: data.total || this.list.length
        }
      } catch (e) {
        this.listError = e?.message || '加载书籍列表失败'
      } finally {
        this.listLoading = false
      }
    },
    async ensureBookDetail(id) {
      if (this.detailMap[id]) return this.detailMap[id]
      if (this.detailLoadingMap[id]) return null
      this.detailLoadingMap[id] = true
      this.detailErrorMap[id] = null
      try {
        const detail = await fetchBookDetail(id)
        this.detailMap[id] = detail
        return detail
      } catch (e) {
        this.detailErrorMap[id] = e?.message || '加载书籍详情失败'
        return null
      } finally {
        this.detailLoadingMap[id] = false
      }
    },
    setActiveBook(id) {
      this.activeBookId = id
    },
    setActiveChapter(chapterId) {
      this.activeChapterId = chapterId
    },
    async loadChapter(bookId, chapterId) {
      if (!bookId || !chapterId) return null
      if (!this.chapterCache[bookId]) this.chapterCache[bookId] = {}
      if (this.chapterCache[bookId][chapterId]) {
        return this.chapterCache[bookId][chapterId]
      }
      try {
        const data = await fetchBookContent(bookId, chapterId)
        // data.chapter 结构期望为单章
        if (data && data.chapter) {
          this.chapterCache[bookId][chapterId] = data.chapter
          return data.chapter
        }
        return null
      } catch (e) {
        return null
      }
    }
  }
})
